package br.pucrio.inf.lac.konoha.hyuga.command;

import com.espertech.esper.client.EPOnDemandQueryResult;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EventBean;

public class SearchCommand extends Command {

	public SearchCommand(String commandSTR, EPServiceProvider cepEngine) {
		super(commandSTR, cepEngine);
	}

	@Override
	public void execute() {
	    if (commandSTR.split(" ").length != 2) {
	        System.out.println("ERROR AT EXECUTING COMMAND: " + commandSTR);
	        System.out.println("CORRECT SYNTAX: SEARCH originalID");
	    }
	    String origID = commandSTR.split(" ")[1];
	    
	    
		String query  = "SELECT * FROM CC AS cell WHERE cell.contains(" + origID + ")";
		
		EPOnDemandQueryResult result = cepEngine.getEPRuntime().executeQuery(query);
		
		if (result.getArray() == null) {
			System.out.println("0 ROWS RETURNED.");
		} else if (result.getArray().length == 0) {
			System.out.println("0 ROWS RETURNED.");
		} else {
		    System.out.println(result.getArray().length + " ROWS RETURNED");
			for (EventBean event : result.getArray()) {
				System.out.println(event.getUnderlying());
			}			
		}

	}

}
